#!/usr/bin/python
import sys
import XenAPI
import base64
import subprocess
import os
path =  "./"

challangefile  = path + "challange"
secret     = path + "secretfile"
ekpub_pem     = path + "ek_pem.pub"
cert       = path + "tpm.cert"
aikblob     = path + "aik_tcpa.pub"
prg        = path + "aikchallenge"

#./aikchallenge secretfile cetrfile verifykey aik_tcpa.pub outchallenge
# Secret file has the user secret

def doexec(args, inputtext=None):
    """Execute a subprocess, then return its return code, stdout and stderr"""
    proc = subprocess.Popen(args,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True)
    (stdout,stderr) = proc.communicate(inputtext)
    rc = proc.returncode
    return (rc,stdout,stderr)

def call_exec():
    (rc,stdout,stderr) = doexec([prg, secret,cert,ekpub_pem,aikblob,challangefile])
    return rc

def main(session):

    rc = call_exec()
    if (rc > 0) :
        print 'Unable to generate Chellange for the XenServer'
        return
    hostlist = session.xenapi.host.get_all()
    hid = 1
    if (len(hostlist) > 1):
        print "\t ## Pool host label names ##\n"
        for x in hostlist:
            print "\t"+session.xenapi.host.get_name_label(x)
        hid = int(raw_input('\n which host?? (enter no from 1)   ::'))
        if ( (hid < 1)  and (hid > (len(hostlist))) ) :
            print "range is 1 to %d" %len(hostlist)
            sys.exit(1)
    host_ref = hostlist[hid-1]
    #host_ref = session.xenapi.session.get_this_host(session.handle)
    f = open(challangefile,"r")
    challange =base64.b64encode(f.read())
    f.close()
    args = {"challange":challange}
    try:
        ret_val = session.xenapi.host.call_plugin(host_ref, 'tpmChallangeAik', 'main', args)
    except:
        print '## Exception in calling TPM Challabge Plugins on Xenserver ##'
        print '## XEN TPM plugins may not be installed ##'
        raise
    print 'IS this the user secret ?? If not XenServer did not pass the TPM challenge.'
    print ret_val
    os.remove(challangefile)

if __name__ == "__main__":
    if len(sys.argv) <> 4:
		print "Usage:"
		print sys.argv[0], "<XenServer host> <username> <password>"
		sys.exit(1)
    url = "https://" + sys.argv[1]
    username = sys.argv[2]
    password = sys.argv[3]
    session = XenAPI.Session(url)
    session.xenapi.login_with_password(username, password)
    try:
        main(session)
    except Exception, e:
        print str(e)
        raise

